<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card id="card">
      <el-row>
        <el-cow>
          <el-button id="btn" type="primary">添加用户</el-button>
        </el-cow>
      </el-row>

      <!-- 角色列表 -->
      <el-table id="table" :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', index === 0 ? 'bdtop' : '']" v-for="(item, index) in scope.row.children"
              :key="item.id">
              <el-col :span="5">
                <el-tag @close="removeDialogById(scope.row, item.id)" closable id="tagItem1">{{ item.authName
                  }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二三级 -->
              <el-col :span="19">
                <el-row :class="['bdbottom', index === 0 ? 'bdtop' : '']" v-for="item2 in item.children"
                  :key="item2.id">
                  <el-col :span="6">
                    <el-tag @close="removeDialogById(scope.row, item2.id)" closable type="success">{{ item2.authName
                      }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag closable v-for="item3 in item2.children" :key="item3.id" type="warning"
                      @close="removeDialogById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>

                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialog(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete"
              @click="deleteRolesById(scope.row.id)">删除</el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button size="mini" type="warning" icon="el-icon-setting"
                @click="showSetRightsDialog(scope.row)">分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>

      </el-table>
    </el-card>

    <!-- 分配角色权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="rightsDialogVisible" width="50%" :before-close="handleClose"
      @close="setRightDialogClosed">
      <el-tree ref="treeRef" :data="rightsList" :props="treeProps" @node-click="handleNodeClick" node-key="id"
        :default-expand-all="true" show-checkbox :default-checked-keys="defKeys"></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      rightsDialogVisible: false,
      rightsList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error("角色列表请求失败")
      this.rolesList = res.data
      // console.log(res);
    },
    async removeDialogById(role, rightsId) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult === 'cancel') return this.$message.info('用户已取消操作')
      if (confirmResult === 'confirm') {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightsId}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        // this.getRolesList() 
        role.children = res.data
      }
    },
    async showSetRightsDialog(role) {

      this.roleId = role.id

      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取用户权限失败')
      // console.log(res.data);
      this.rightsList = res.data
      this.getLeafKeys(role, this.defKeys)
      this.rightsDialogVisible = true

    },
    // 以递归方式将数据保存到defKeys数组中
    getLeafKeys(node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      });
    },
    setRightDialogClosed() {
      this.defKeys = []
    },
    async allotRights() {

      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keysStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: keysStr })
      if (res.meta.status!==200) return this.$message.error("分配权限失败")
      this.$message.success("分配权限成功")
      this.getRolesList()
      this.rightsDialogVisible = false
    }

  }

}
</script>

<style lang="less" scoped>
#tagItem1 {
  margin-left: 20%;
}

.el-tag {
  margin: 3px;
}

.el-row {
  display: flex;
  justify-content: center;
  align-items: center;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

#btn {
  position: absolute;
  left: 0;
}

#table {
  margin-top: 50px;
}
</style>